import { login, logout, getInfo, wechatLogin } from 'src/api/user'
import { getToken, setToken, removeToken } from 'src/utils/auth'
import { clearSessionVal } from 'src/utils/session'
import router, { resetRouter } from 'src/router'


const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        type: '',
        orgs: '',
        menu: [],
        id: null,
        btnPermissions: []


    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_TYPE: (state, type) => {
        state.type = type
    },
    SET_ORGS: (state, orgs) => {
        state.orgs = orgs
    },
    SET_MENU: (state, menu) => {
        state.menu = menu
    },
    SET_ID: (state, id) => {
        state.id = id
    },
    SET_BTN: (state, btnPermissions) => {
        state.btnPermissions = btnPermissions
    }

}

const actions = {
    login({ commit }, userInfo) {
        const { username, password,clientId,captcha } = userInfo
        return new Promise((resolve, reject) => {
            login(userInfo).then(response => {
                const { data } = response
                // 将 token 存入 vuex
                commit('SET_TOKEN', data.token)
                // 将 token 存入 Cookies
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    wechatLogin({ commit }, ticket) {
        return new Promise((resolve, reject) => {
            wechatLogin({ ticket: ticket }).then(response => {
                const { data } = response
                if (data.state == 1 && data.token != null) {
                    commit('SET_TOKEN', data.token)
                    setToken(data.token)
                }
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(data => {

                if (data.code !== 20000) {
                    return reject(data.message)
                }

                const {avatar, type,id,nickName, menu ,orgs} = data.data

                // if (!menu || menu.length <= 0) {
                //     reject('抱歉，您的账户已被停用！')
                // }

                let arr = [
                    {
                        component: "",
                        hidden: 1,
                        icon: "el-icon-data-analysis",
                        id: 10211,
                        menuName: "数据大屏",
                        menuType: "M",
                        meta: "",
                        orderNum: 0,
                        parentId: 0,
                        path: "/dashboard-fullscreen3453",
                        perms: "",
                        status: 1
                    }
                ]
                if (!menu || menu.length <= 0) {
                    commit('SET_MENU', arr)
                }else {
                    commit('SET_MENU', menu)
                }

                commit('SET_BTN', btnPermissionsArr(menu))
                commit('SET_NAME', nickName)
                commit('SET_AVATAR', avatar)
                commit('SET_TYPE', type)
                commit('SET_ID', id)
                commit('SET_ORGS', orgs)
                resolve(data.data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    logout({ commit, state }) {
        return new Promise((resolve, reject) => {

            commit('SET_TOKEN', '')
            commit('SET_MENU', [])
            removeToken()
            resetRouter()
            clearSessionVal()
            resolve()
        })
    },

    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_MENU', [])
            removeToken()
            resolve()
        })
    },

    async changeRoles({ commit, dispatch }, role) {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getInfo')
        resetRouter()

        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
        router.addRoutes(accessRoutes)
        dispatch('tagsView/delAllViews', null, { root: true })
    }
}


const btnPermissionsArr = (menu) => {
    let arr = []
    menu.forEach(item => {
        if (item.perms && item.perms != '') {
            arr.push(item.perms)
        }
        if (item.children&&item.children.length) {
            arr = arr.concat(btnPermissionsArr(item.children))
        }
    })
    return arr
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}

